package com.java.design;

/**
 * 组合模式有时又叫部分-整体模式在处理类似树形结构的问题时比较方便，看看关系图：
 * 
 * @author Administrator
 *
 */

class TreeNode {
	private String name;
	private TreeNode parent;
	private TreeNode left;
	private TreeNode right;

	public TreeNode(String name, TreeNode parent) {
		this.name = name;
		this.parent = parent;
	}

	public void setLeft(TreeNode left) {
		this.left = left;
	}

	public TreeNode getLeft() {
		return left;
	}

	public void setRight(TreeNode right) {
		this.right = right;
	}

	public TreeNode getRight() {
		return right;
	}

	public String getName() {
		return name;
	}
}

class Tree {
	private TreeNode root = null;

	public Tree(String rootName) {
		this.root = new TreeNode(rootName, null);
	}

	// 创建一个完成二叉树
	private void createTree(TreeNode parent, int nBeginLevel, int nEndLevel) {
		if (nBeginLevel == nEndLevel)
			return;
		// 创建左边节点
		TreeNode left = new TreeNode(nBeginLevel + "-left", parent);
		parent.setLeft(left);
		// 创建右边节点
		TreeNode right = new TreeNode(nBeginLevel + "-right", parent);
		parent.setRight(right);
		// 创建左边节点的树
		createTree(left, nBeginLevel + 1, nEndLevel);
		// 创建右边节点的树
		createTree(right, nBeginLevel + 1, nEndLevel);
	}

	// 创建一个完成二叉树
	public void createTree(int treeHight) {
		createTree(root, 1, treeHight + 1);
	}

	// 打印树
	private void pritTree(TreeNode root, String blank) {
		if (root == null)
			return;
		// 打印父节点
		System.out.println(blank + root.getName());
		// 打印左节点
		pritTree(root.getLeft(), blank + blank);
		// 打印右节点
		pritTree(root.getRight(), blank + blank);
	}

	// 打印树
	public void pritTree() {
		pritTree(root, " ");
	}
}

public class CompositeMode {
	public static void main(String[] args) {
		Tree tree = new Tree("root");
		tree.createTree(2);
		tree.pritTree();
	}
}
